package com.bjxst.filter;

import com.alibaba.fastjson.JSONObject;
import com.google.common.net.HttpHeaders;
import org.apache.commons.lang.StringUtils;
import org.reactivestreams.Publisher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.Set;

@Component
public class JwtCheckFilter implements GlobalFilter, Ordered {

    @Autowired
  private StringRedisTemplate redisTemplate;
   @Value("${no.require.urls:/admin/login},/user/gt/register,/user/login,/user/sms/sendTo,/user/users/register")
    private Set<String> noRequireTokenUris;


    /**
     * 过滤器拦截请求做啥
     * @param exchange
     * @param chain
     * @return
     */

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {


        //1 该接口是否需要token访问
        if(!isRequireToken(exchange))
        {
            return  chain.filter(exchange);
        }
        //2. 如果需要token访问，取出token
        String token = getUserToken(exchange);
        //3.判断token是否有效
        if(StringUtils.isEmpty(token))
        {
            return buildeNoAuthroizationResult(exchange);
        }
        Boolean hasKey = redisTemplate.hasKey(token);
        if(hasKey!=null&&hasKey)
        {
            return  chain.filter(exchange);
        }
        return null;
    }

    /**
     * 相应无token错误
     * @return
     */

    private Mono<Void> buildeNoAuthroizationResult(ServerWebExchange exchange) {
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().set("Content-Type","application/json");
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("error","NoAuthroization ");
        jsonObject.put("errorMsg","Token is NULL");
       DataBuffer wrap =  response.bufferFactory().wrap(jsonObject.toJSONString().getBytes());
        return response.writeWith(Flux.just(wrap)) ;
    }

    private String getUserToken(ServerWebExchange exchange) {
        String token= exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        return token == null?null:token.replace("bearer ","");
    }

    /**
     *
     */
    private boolean isRequireToken(ServerWebExchange exchange)
    {
        String path = exchange.getRequest().getURI().getPath();
        if (noRequireTokenUris.contains(path))
        {
            return false; //不需要token
        }
        return  true;
    }


    /**
     * 拦截器顺序
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
